package com.qunar.dyds.controller;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;

import com.qunar.base.meerkat.util.PropertyUtil;
import com.qunar.dyds.service.CompetitorService;
import com.qunar.dyds.service.InviteCodeService;
import com.qunar.dyds.service.ReportService;
import com.qunar.dyds.service.RequestService;

public abstract class AbstractController {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    protected CompetitorService competitorService;

    @Resource
    protected RequestService requestService;

    @Resource
    protected ReportService reportService;

    @Resource
    protected InviteCodeService inviteCodeService;

    // JSON响应状态
    protected static final int STATUS_OK = 0;
    protected static final int STATUS_ERROR = 1;

    protected static final Pattern PATTERN_CODE = Pattern
            .compile(PropertyUtil.getProperty("pattern.invitecode", "DYDS_[0-9]{4}"));

    protected static final Pattern PATTERN_USERNAME = Pattern.compile("[0-9a-zA-z]{2,16}");

    private Map<Object, Object> data(Object... data) {
        Map<Object, Object> map = new LinkedHashMap<Object, Object>();

        if (data.length % 2 != 0) {
            return map;
        }

        for (int i = 0; i < data.length; i += 2) {
            map.put(data[i], data[i + 1]);
        }
        return map;
    }

    protected Map<Object, Object> json(int status, String message) {
        return data("status", status, "message", message);
    }

    protected Map<Object, Object> dataJson(Object data) {
        return data("status", STATUS_OK, "data", data);
    }

    /**
     * 数据非法导致操作失败
     */
    protected Map<Object, Object> errorJson(String message) {
        return data("status", STATUS_ERROR, "message", message);
    }

    protected ModelAndView errorView(String message) {
        logger.error(message);
        return new ModelAndView("site/error", "message", message);
    }
}
